package com.linkivr.action;

import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Component;

import com.linkivr.util.GL;
import com.linkivr.model.*;
import com.linkivr.service.*;

@Component("currDataAction")
public class CurrDataAction extends MyAction {
	private static final long serialVersionUID = 1L;
	private CurrDataService service;
	private AppService appService;
	private ComportService comportService;
	private ModuleService moduleService;
	private ChannelService channelService;

	public CurrDataService getService() {
		return service;
	}

	@Resource
	public void setService(CurrDataService service) {
		this.service = service;
	}

	public AppService getAppService() {
		return appService;
	}

	@Resource
	public void setAppService(AppService appService) {
		this.appService = appService;
	}

	public ComportService getComportService() {
		return comportService;
	}

	@Resource
	public void setComportService(ComportService comportService) {
		this.comportService = comportService;
	}

	public ModuleService getModuleService() {
		return moduleService;
	}

	@Resource
	public void setModuleService(ModuleService moduleService) {
		this.moduleService = moduleService;
	}

	public ChannelService getChannelService() {
		return channelService;
	}

	@Resource
	public void setChannelService(ChannelService channelService) {
		this.channelService = channelService;
	}

	public String list() throws IOException {
		GL.info("user.list()函数  ");
		beginReqParam();

		List<T_curr_data> tabObjs = service.queryAll(start, limit);

		jsonString = "{totalProperty:" + service.queryCount() + ",root:[";
		int i = 0;
		for (T_curr_data to : tabObjs) {

			if (i != 0 && i != tabObjs.size())
				jsonString = jsonString + ",";
			i++;
			String t = "{id:'" + to.getId() + "',app_id:'" + to.getApp_id()
					+ "',com_id:'" + to.getCom_id() + "',com_addr:'"
					+ to.getCom_addr() + "',chn0:'" + to.getChn0() + "',chn1:'"
					+ to.getChn1() + "',chn2:'" + to.getChn2() + "',chn3:'"
					+ to.getChn3() + "',chn4:'" + to.getChn4() + "',chn5:'"
					+ to.getChn5() + "',chn6:'" + to.getChn6() + "',chn7:'"
					+ to.getChn7() + "',createtime:'" + to.getCreatetime()
					+ "'}";
			jsonString = jsonString + t;
		}
		jsonString += "]}";
		out.write(jsonString);
		GL.info(jsonString);
		endReqParam();
		return null;
	}

	private String getChnState(T_channel channel, double cdata) {
		double l1 = channel.getFactor().getFac_alarm_lower1();
		double u1 = channel.getFactor().getFac_alarm_upper1();
		double l2 = channel.getFactor().getFac_alarm_lower2();
		double u2 = channel.getFactor().getFac_alarm_upper2();
		String state = "正常";
		if (cdata <= l1) {
			state = "下限预警";
			if (cdata <= l2) {
				state = "下限告警";
			}
		} else if (cdata >= u1) {
			state = "上限预警";
			if (cdata >= u2) {
				state = "上限告警";
			}
		}

		return state;
	}

	public String list2() throws IOException {
		GL.info("user.list()函数  ");
		beginReqParam();

		String f_p_id = request.getParameter("p_id");

		T_channel channel = channelService.query(Integer.parseInt(f_p_id));
		int app_id = channel.getModule().getComport().getApp().getApp_id();
		int com_id = channel.getModule().getComport().getCom_id();
		int com_addr = channel.getModule().getCom_addr();
		int chn_id = channel.getChn_id();

		List<T_curr_data> tabObjs = service.queryAll(start, limit, app_id,
				com_id, com_addr);

		jsonString = "{totalProperty:" + service.queryCount() + ",root:[";
		int i = 0;
		double[] d8 = new double[8];
		for (T_curr_data to : tabObjs) {

			if (i != 0 && i != tabObjs.size())
				jsonString = jsonString + ",";
			i++;
			d8[0] = to.getChn0();
			d8[1] = to.getChn1();
			d8[2] = to.getChn2();
			d8[3] = to.getChn3();
			d8[4] = to.getChn4();
			d8[5] = to.getChn5();
			d8[6] = to.getChn6();
			d8[7] = to.getChn7();

			String state = getChnState(channel, d8[chn_id]);

			String t = "{id:'" + to.getId() + "',app_id:'" + to.getApp_id()
					+ "',com_id:'" + to.getCom_id() + "',com_addr:'"
					+ to.getCom_addr() + "',chn_state:'" + state
					+ "',chn_data:'" + d8[chn_id] + "',createtime:'"
					+ to.getCreatetime() + "'}";
			jsonString = jsonString + t;
		}
		jsonString += "]}";
		out.write(jsonString);
		GL.info(jsonString);
		endReqParam();
		return null;
	}

	public String export2() throws IOException, ParseException {
		GL.info("currdata.export2()函数  ");
		beginReqParam();

		String f_p_id = request.getParameter("p_id");
		GL.info("p_id="+f_p_id);
		String[] idarray = f_p_id.split("-");
		String p_starttime = request.getParameter("p_starttime");
		GL.info("p_starttime="+p_starttime);
		String p_endtime = request.getParameter("p_endtime");
		GL.info("p_endtime="+p_endtime);

		

		// 创建一个新的Excel
		HSSFWorkbook workBook = new HSSFWorkbook();
		
		for(int i=0;i<idarray.length;i++){
			int pid = Integer.parseInt(idarray[i]);
			T_channel channel = channelService.query(pid);
			// 创建sheet页
			HSSFSheet sheet = workBook.createSheet();	
			// sheet页名称
			workBook.setSheetName(i, channel.getChn_name());
			addSheet2(sheet,pid,p_starttime,p_endtime);
		}


		// 通过Response把数据以Excel格式保存
		response.reset();
		response.setContentType("application/msexcel;charset=UTF-8");
		try {
			response.addHeader(
					"Content-Disposition",
					"attachment;filename=\""
							+ new String(("监控数据" + ".xls").getBytes("GBK"),
									"ISO8859_1") + "\"");
			OutputStream outs = response.getOutputStream();
			workBook.write(outs);
			outs.flush();
			outs.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		endReqParam();
		return null;
	}	
	
	private void setChnValue(T_module module, double[] datas) {
		for (int i = 0; i < 8; i++) {
			T_channel channel = channelService.query(i, module.getMod_id());
			if (channel == null) {
				continue;
			}
//			double rl = channel.getFactor().getFac_range_lower();
//			double ru = channel.getFactor().getFac_range_upper();
//			double dl = channel.getFactor().getFac_dev_lower();
//			double du = channel.getFactor().getFac_dev_upper();
//
//			double trueData =((ru-rl)/(du-dl))*(datas[i]-dl)+rl;
			double trueData = datas[i];

			channel.setLastData(trueData);
			channel.setUpdateTime(new Date());
			String state = getChnState(channel, trueData);
			channel.setChn_state(state);

			String loginfo = module.getMod_name() + "_" + i + ":" + datas[i]
					+ "," + state;
			GL.info(loginfo);

			channelService.update(channel);

		}
	}

	public String add() throws IOException {
		GL.info("add()函数  ");
		String jsonString = "";
		beginReqParam();

		String f_app_id = request.getParameter("f_app_id");
		String f_login_name = request.getParameter("f_login_name");
		String f_login_passwd = request.getParameter("f_login_passwd");
		String f_com_id = request.getParameter("f_com_id");
		String f_com_addr = request.getParameter("f_com_addr");

		String f_chn0 = request.getParameter("f_chn0");
		String f_chn1 = request.getParameter("f_chn1");
		String f_chn2 = request.getParameter("f_chn2");
		String f_chn3 = request.getParameter("f_chn3");
		String f_chn4 = request.getParameter("f_chn4");
		String f_chn5 = request.getParameter("f_chn5");
		String f_chn6 = request.getParameter("f_chn6");
		String f_chn7 = request.getParameter("f_chn7");

		String postinfo = String.format(
				"%s,%s,%s,%s,%s:%s,%s,%s,%s,%s,%s,%s,%s", f_app_id,
				f_login_name, f_login_passwd, f_com_id, f_com_addr, f_chn0,
				f_chn1, f_chn2, f_chn3, f_chn4, f_chn5, f_chn6, f_chn7);
		GL.info(postinfo);

		int appid = Integer.parseInt(f_app_id);
		int comid = Integer.parseInt(f_com_id);
		int comaddr = Integer.parseInt(f_com_addr);

		T_app app = appService.query(appid);
		T_comport comport = null;
		T_module module = null;
		if (app != null) {
			comport = comportService.query(comid, appid);
		}
		if (comport != null) {
			module = moduleService.query(comaddr, comport.getId());
		}

		if ((module != null) && app.getLogin_name().equals(f_login_name)
				&& app.getLogin_passwd().equals(f_login_passwd)) {
			T_curr_data to = new T_curr_data();
			to.setApp_id(appid);
			to.setCom_id(comid);
			to.setCom_addr(comaddr);
			to.setCreatetime(new Date());

			double[] datas = new double[8];
			datas[0] = Double.parseDouble(f_chn0);
			datas[1] = Double.parseDouble(f_chn1);
			datas[2] = Double.parseDouble(f_chn2);
			datas[3] = Double.parseDouble(f_chn3);
			datas[4] = Double.parseDouble(f_chn4);
			datas[5] = Double.parseDouble(f_chn5);
			datas[6] = Double.parseDouble(f_chn6);
			datas[7] = Double.parseDouble(f_chn7);

			to.setChn0(datas[0]);
			to.setChn1(datas[1]);
			to.setChn2(datas[2]);
			to.setChn3(datas[3]);
			to.setChn4(datas[4]);
			to.setChn5(datas[5]);
			to.setChn6(datas[6]);
			to.setChn7(datas[7]);

			service.add(to);

			setChnValue(module, datas);

			jsonString = "{success: true ,msg:'Success'}";
		} else {
			jsonString = "{failure: false ,msg:'failed，no module exist or wrong name and password'}";
		}

		out.write(jsonString);
		GL.info(jsonString);
		endReqParam();
		return null;

	}

	@SuppressWarnings("deprecation")
	private void addSheet(HSSFSheet sheet,String stime,String etime ) throws ParseException {
		
		SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟  
		Date starttime=sdf2.parse(stime);
		Date endtime=sdf2.parse(etime);

		List<T_curr_data> currdatas = service.queryAll(starttime, endtime);
		// 创建header页
		HSSFHeader header = sheet.getHeader();
		// 设置标题居中
		header.setCenter("标题");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		// 设置第一行为Header
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell0 = row.createCell(Short.valueOf("0"));
		HSSFCell cell1 = row.createCell(Short.valueOf("1"));
		HSSFCell cell2 = row.createCell(Short.valueOf("2"));
		HSSFCell cell3 = row.createCell(Short.valueOf("3"));
		HSSFCell cell4 = row.createCell(Short.valueOf("4"));
		HSSFCell cell5 = row.createCell(Short.valueOf("5"));
		HSSFCell cell6 = row.createCell(Short.valueOf("6"));
		HSSFCell cell7 = row.createCell(Short.valueOf("7"));
		HSSFCell cell8= row.createCell(Short.valueOf("8"));
		HSSFCell cell9 = row.createCell(Short.valueOf("9"));
		HSSFCell cell10 = row.createCell(Short.valueOf("10"));
		HSSFCell cell11 = row.createCell(Short.valueOf("11"));
		HSSFCell cell12 = row.createCell(Short.valueOf("12"));
		// 设置字符集
		// cell0.setEncoding(HSSFCell.ENCODING_UTF_16);
		// cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
		// cell2.setEncoding(HSSFCell.ENCODING_UTF_16);

		cell0.setCellValue("编号");
		cell1.setCellValue("应用程序编号");
		cell2.setCellValue("串口号");
		cell3.setCellValue("串口地址");
		cell4.setCellValue("通道0");
		cell5.setCellValue("通道1");
		cell6.setCellValue("通道2");
		cell7.setCellValue("通道3");
		cell8.setCellValue("通道4");
		cell9.setCellValue("通道5");
		cell10.setCellValue("通道6");
		cell11.setCellValue("通道7");
		cell12.setCellValue("创建时间");
		
		if (currdatas != null && !currdatas.isEmpty()) {
			for (int i = 0; i < currdatas.size(); i++) {
				T_curr_data curr_data = currdatas.get(i);
				row = sheet.createRow(i + 1);
				cell0 = row.createCell(Short.valueOf("0"));
				cell1 = row.createCell(Short.valueOf("1"));
				cell2 = row.createCell(Short.valueOf("2"));
				cell3 = row.createCell(Short.valueOf("3"));
				cell4 = row.createCell(Short.valueOf("4"));
				cell5 = row.createCell(Short.valueOf("5"));
				cell6 = row.createCell(Short.valueOf("6"));
				cell7 = row.createCell(Short.valueOf("7"));
				cell8 = row.createCell(Short.valueOf("8"));
				cell9 = row.createCell(Short.valueOf("9"));
				cell10 = row.createCell(Short.valueOf("10"));
				cell11 = row.createCell(Short.valueOf("11"));
				cell12 = row.createCell(Short.valueOf("12"));

				cell0.setCellValue(curr_data.getId());
				cell1.setCellValue(curr_data.getApp_id());
				cell2.setCellValue(curr_data.getCom_id());
				cell3.setCellValue(curr_data.getCom_addr());
				cell4.setCellValue(curr_data.getChn0());
				cell5.setCellValue(curr_data.getChn1());
				cell6.setCellValue(curr_data.getChn2());
				cell7.setCellValue(curr_data.getChn3());
				cell8.setCellValue(curr_data.getChn4());
				cell9.setCellValue(curr_data.getChn5());
				cell10.setCellValue(curr_data.getChn6());
				cell11.setCellValue(curr_data.getChn7());
				cell12.setCellValue(sdf.format(curr_data.getCreatetime()));

				sheet.setColumnWidth((short) 0, (short) 2000);
				sheet.setColumnWidth((short) 1, (short) 3000);
				sheet.setColumnWidth((short) 2, (short) 2000);
				sheet.setColumnWidth((short) 3, (short) 2000);
				sheet.setColumnWidth((short) 4, (short) 2000);
				sheet.setColumnWidth((short) 5, (short) 2000);
				sheet.setColumnWidth((short) 6, (short) 2000);
				sheet.setColumnWidth((short) 7, (short) 2000);
				sheet.setColumnWidth((short) 8, (short) 2000);
				sheet.setColumnWidth((short) 9, (short) 2000);
				sheet.setColumnWidth((short) 10, (short) 2000);
				sheet.setColumnWidth((short) 11, (short) 2000);
				sheet.setColumnWidth((short) 12, (short) 5000);
			}
		}
	}
	
	@SuppressWarnings("deprecation")
	private void addSheet2(HSSFSheet sheet,int pid,String stime,String etime ) throws ParseException {
		
		SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟  
		Date starttime=sdf2.parse(stime);
		Date endtime=sdf2.parse(etime);
		
		T_channel channel = channelService.query(pid);
		int app_id = channel.getModule().getComport().getApp().getApp_id();
		int com_id = channel.getModule().getComport().getCom_id();
		int com_addr = channel.getModule().getCom_addr();
		int chn_id = channel.getChn_id();

		List<T_curr_data> tabObjs = service.queryAll(app_id,	com_id, com_addr,starttime,endtime);
		
		// 创建header页
		HSSFHeader header = sheet.getHeader();
		// 设置标题居中
		header.setCenter("标题");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		// 设置第一行为Header
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell0 = row.createCell(Short.valueOf("0"));
		HSSFCell cell1 = row.createCell(Short.valueOf("1"));
		HSSFCell cell2 = row.createCell(Short.valueOf("2"));

		cell0.setCellValue("数据");
		cell1.setCellValue("状态");
		cell2.setCellValue("上传时间");
		
		int i = 0;
		double[] d8 = new double[8];
		for (T_curr_data to : tabObjs) {

			d8[0] = to.getChn0();
			d8[1] = to.getChn1();
			d8[2] = to.getChn2();
			d8[3] = to.getChn3();
			d8[4] = to.getChn4();
			d8[5] = to.getChn5();
			d8[6] = to.getChn6();
			d8[7] = to.getChn7();

			String state = getChnState(channel, d8[chn_id]);

			row = sheet.createRow(i + 1);
			cell0 = row.createCell(Short.valueOf("0"));
			cell1 = row.createCell(Short.valueOf("1"));
			cell2 = row.createCell(Short.valueOf("2"));

			cell0.setCellValue(d8[chn_id]);
			cell1.setCellValue(state);
			cell2.setCellValue(sdf.format(to.getCreatetime()));

			sheet.setColumnWidth((short) 0, (short) 3000);
			sheet.setColumnWidth((short) 1, (short) 3000);
			sheet.setColumnWidth((short) 2, (short) 5000);
			i++;
		}
	}

	public String export() throws Exception {
		// 获取问题列表
		GL.info("export()函数 ");
		beginReqParam();
		
		String p_starttime = request.getParameter("p_starttime");
		GL.info("p_starttime="+p_starttime);
		String p_endtime = request.getParameter("p_endtime");
		GL.info("p_endtime="+p_endtime);

		// 创建一个新的Excel
		HSSFWorkbook workBook = new HSSFWorkbook();
		// 创建sheet页
		HSSFSheet sheet = workBook.createSheet();	
		// sheet页名称
		workBook.setSheetName(0, "Data");
		addSheet(sheet,p_starttime,p_endtime);

		// 通过Response把数据以Excel格式保存
		response.reset();
		response.setContentType("application/msexcel;charset=UTF-8");
		try {
			response.addHeader(
					"Content-Disposition",
					"attachment;filename=\""
							+ new String(("原始数据" + ".xls").getBytes("GBK"),
									"ISO8859_1") + "\"");
			OutputStream outs = response.getOutputStream();
			workBook.write(outs);
			outs.flush();
			outs.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		endReqParam();

		return null;
	}

}
